<template>
	<view class="cu-modal bottom-modal" :class="modalSku ? 'show' : ''" @tap="hideModalSku" catchtouchmove="touchMove"
		style="z-index: 992">
		<view class="cu-dialog dialo-sku bg-white" :class="modalSku ? 'animation-slide-bottom' : ''" @tap.stop>
			<view class="cu-card article no-card" style="height: 30%">
				<view class="cu-item">
					<view class="content">
						<image
							:src="goodsSpu.picUrls && goodsSpu.picUrls.length > 0 ? goodsSpu.picUrls[0] ? goodsSpu.picUrls[0]: '/static/image/no_pic.png':'/static/image/no_pic.png'"
							mode="aspectFill" class="row-img margin-top-xs" v-if="!goodsSku || !goodsSku.salesPrice">
						</image>
						<image
							:src="goodsSku.picUrl? goodsSku.picUrl : goodsSpu.picUrls && goodsSpu.picUrls.length > 0 && goodsSpu.picUrls[0] ? goodsSpu.picUrls[0]:'/static/image/no_pic.png'"
							mode="aspectFill" class="row-img margin-top-xs" v-if="goodsSku && goodsSku.salesPrice">
						</image>
						<view class="desc">
							<view class="text-price margin-top-xl text-bold text-red text-xl" v-show="!goodsSku || !goodsSku.salesPrice">
							  <text>{{ goodsSpu.priceDown}}</text>
							  <text v-show="goodsSpu.priceDown != goodsSpu.priceUp"	class="text-red margin-lr-xs">-</text>
							  <text v-show="goodsSpu.priceDown != goodsSpu.priceUp"	class="text-red text-bold">{{ goodsSpu.priceUp }}</text>
							</view>
							<view class="text-price margin-top-xl text-bold text-red text-lg"
								v-show="goodsSku && goodsSku.salesPrice">
								<text v-if="!goodsSpu.marketingPrice || activityId">{{goodsSku.salesPrice}}</text>
								<text v-else>{{goodsSpu.marketingPrice}}</text>
							</view>
							<view class="text-gray text-sm">库存{{ newData ? newData.stockNum : 0 }}件</view>
							<view class="text-black text-sm">
								<text v-if="goodsSpecData.length">选择</text>
								<view class="display-ib" v-for="(item, index) in goodsSpecData" :key="index">
									<view class="display-ib" v-show="!item.checked">{{ item.value }}</view>
									<view class="display-ib" v-show="item.checked" v-for="(item2, index2) in item.leaf"
										:key="index2">
										<view class="display-ib" v-show="item.checked == item2.id">{{ item2.value }}
										</view>
									</view>
									<view class="display-ib" v-show="goodsSpecData.length != index + 1">,</view>
								</view>
							</view>
							<view> </view>
						</view>
					</view>
				</view>
				<view class="text-xl close-icon">
					<text class="cuIcon-close" @tap="hideModalSku"></text>
				</view>
			</view>
			<scroll-view scroll-y scroll-with-animation style="height: 60%">
				<!-- 如果不这样会不刷新数据 -->
				<view v-show="false">{{ goodsSpecData }}</view>
				<view class="padding-bottom-xs solid-top" v-for="(item, index) in goodsSpecData" :key="index">
					<view class="cu-bar bg-white" style="min-height: 80rpx">
						<view class="action">
							<text class="text-black">{{ item.value }}</text>
						</view>
					</view>
					<view class="grid bg-white margin-lr-sm">
						<button class="cu-btn margin-xs" :class="item.checked == item2.id ? 'line-red' : ''"
							v-for="(item2, index2) in item.leaf" :key="index2"
							@tap="skuClick(item2, index, $event, index2)" :data-index="index" :data-index2="index2"
							:disabled="item2.disabled">
							{{ item2.value }}
						</button>
					</view>
				</view>				
			</scroll-view>
			<view class="cu-bar bg-white tabbar border shop foot" style="height: 10%">
				<view class="btn-group" v-if="modalSkuType == ''">
					<button class="cu-btn bg-orange round shadow-blur m-sku-bn lg" @tap="toDo" data-type="1"
						:disabled="goodsSku.enable == '0'" type>
						加入购物车
					</button>
					<button class="cu-btn round shadow-blur m-sku-bn lg" :class="'bg-' + theme.themeColor" @tap="toDo"
						data-type="2" :disabled="(newData ? newData.stockNum : 0) <= 0 || goodsSku.enable == '0'" type>
						立即购买
					</button>
				</view>
				<view class="btn-group" v-if="modalSkuType != ''">
					<button class="cu-btn round shadow-blur lg" :class="'bg-' + theme.themeColor" style="width: 90%"
						@tap="checkQuota" :data-id="newData ? newData.stockNum : 0" type :data-type="modalSkuType">
						确定
					</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	const app = getApp();
	import api from 'utils/api'

	export default {
		data() {
			return {
				CustomBar: this.CustomBar,
				theme: app.globalData.theme, //全局颜色变量
				initFirst: true, //只初始化一次
				choiceAll: false, //是否选择全部
				difference: [], //sku列表
				shopItemInfo: {}, //存放要和选中的值进行匹配的数据
				selectArr: [], //存放被选中的值
				subIndex: [], //是否选中 因为不确定是多规格还是单规格，所以这里定义数组来判断
				selectshop: {}, //存放最后选中的商品
				// newData:undefined,
				newData: {},
				prescript: '',
			};
		},
		onLoad() {

		},
		created() {},		
		computed: {

		},
		props: {
			shopInfo: {
				type: Object,
				default: () => {}
			},
			goodsSpu: {
				type: Object,
				default: () => {}
			},
			goodsSpecData: {
				type: Array,
				default: () => []
			},
			goodsSku: {
				type: Object,
				default: () => ''
			},
			activityId: {
				default: undefined
			},
			modalSku: {
				type: Boolean,
				default: false
			},
			modalSkuType: {
				type: String,
				default: ''
			},
			cartNum: {
				type: Number,
				default: 1
			},
			shoppingCartId: {
				type: String,
				default: null
			},
			shopId: {
				type: String,
				default: ''
			}
		},
		created() {
			// mounted() {
			let that = this
			uni.$on('stock', function(data) {
				that.newData = data
			})

		},
		watch: {
			goodsSpu(val, oldVal) {},
			goodsSku(val) {},
			goodsSpecData(val, oldVal) { // 这个数据是最后请求的，所以这个有数据表示就能初始化规格数据了，initFirst：监控是否重复初始化数据
				if (val != oldVal && this.initFirst) {
					this.initSpecData();
				}
			},
		},
		methods: {
			initSpecData(goodsSpecData) {
				if (goodsSpecData) {
					if (this.goodsSpecData.length > 0) {
						this.goodsSpecData.splice(0, this.goodsSpecData.length);
					}
					goodsSpecData.map(item => {
						this.goodsSpecData.push(item);
					});
				}
				if (this.goodsSpu && this.goodsSpu.skus) {
					this.initFirst = false;
					// this.difference: [], //sku列表 {"id": "23","price": 500,"stock": 48,"difference": ["100","绿色","X","豪华"]}
					this.shopItemInfo = {}, //存放要和选中的值进行匹配的数据
						this.selectArr = [], //存放被选中的值
						this.subIndex = []; //是否选中 因为不确定是多规格还是单规格，所以这里定义数组来判断
					//初始化数据
					if (this.goodsSpecData.length > 0) {
						this.goodsSpecData.map(item => {
							item.diabled = false; //是否点击
							item.ishow = true; //是否显示，暂时无用
							this.selectArr.push(item.checked ? item.checked : '');
							this.subIndex.push(-1);
						});
					}
					this.changeData(this.goodsSpu.skus)
					this.checkItem(); //计算sku里面规格形成路径
					this.checkInpath(-1); //传-1是为了不跳过循环
				}
			},
			changeData(differenceList) {
				for (let item of differenceList) {
					let nowOneCompound = []
					for (let oneCompound of item.specs) {
						nowOneCompound.push(oneCompound.specValueId)
					}
					item.difference = nowOneCompound
				}
			},
			checkItem() {
				// console.time('计算有多小种可选路径需要的时间是');
				//计算有多小种可选路径
				let result = this.goodsSpu.skus.reduce(
					(arrs, items) => {
						return arrs.concat(
							items.difference.reduce(
								(arr, item) => {
									return arr.concat(
										arr.map(item2 => {
											//利用对象属性的唯一性实现二维数组去重
											if (!this.shopItemInfo.hasOwnProperty([...item2, item])) {
												this.shopItemInfo[[...item2, item]] = items;
											}
											return [...item2, item];
										})
									);
								},
								[
									[]
								]
							)
						);
					},
					[
						[]
					]
				);
				// console.timeEnd('计算有多小种可选路径需要的时间是');
			},
			checkInpath(clickIndex) {
				// console.time('筛选可选路径需要的时间是');
				//循环所有属性判断哪些属性可选
				//当前选中的兄弟节点和已选中属性不需要循环
				for (let i = 0, len = this.goodsSpecData.length; i < len; i++) {
					if (i == clickIndex) {
						continue;
					}
					let len2 = this.goodsSpecData[i].leaf.length;
					for (let j = 0; j < len2; j++) {
						if (this.subIndex[i] != -1 && j == this.subIndex[i]) {
							continue;
						}
						let choosed_copy = [...this.selectArr];
						this.$set(choosed_copy, i, this.goodsSpecData[i].leaf[j].id);
						let choosed_copy2 = choosed_copy.filter(item => item !== '' && typeof item !== 'undefined');
						if (this.shopItemInfo.hasOwnProperty(choosed_copy2)) {
							this.$set(this.goodsSpecData[i].leaf[j], 'ishow', true);
							this.$set(this.goodsSpecData[i].leaf[j], 'disabled', false);
						} else {
							this.$set(this.goodsSpecData[i].leaf[j], 'ishow', false);
							this.$set(this.goodsSpecData[i].leaf[j], 'disabled', true);
						}
					}
				}
				// console.log(this.goodsSpecData)
				// console.timeEnd('筛选可选路径需要的时间是');
			},
			skuClick(value, index1, event, index2) {
				this.goodsSpecData[index1].checked = this.goodsSpecData[index1].checked == value.id ? '' : value
					.id; //已选择过的可以取消
				if (value.ishow) {
					if (this.selectArr[index1] != value.id) {
						this.$set(this.selectArr, index1, value.id);
						this.$set(this.subIndex, index1, index2);
					} else {
						this.$set(this.selectArr, index1, '');
						this.$set(this.subIndex, index1, -1);
					}
					this.checkInpath(index1);
					// 如果全部选完
					if (this.selectArr.every(item => item != '')) {
						this.selectshop = this.shopItemInfo[this.selectArr];
						if (this.selectshop) { //是否有商品 sku
							if (this.selectshop.stock == 0) {
								this.$emit('numChange', 0);
							} else {
								if (this.cartNum > this.selectshop.stock) { // 如果已选择的数量大于库存数量，那么选择的数量直接使用最大库存数量
									this.$emit('numChange', this.selectshop.stock);
								} else if (this.cartNum == 0) {
									this.$emit('numChange', 1);
								}
							}
							this.$emit('changeGoodsSku', this.selectshop);
						} else {
							this.$emit('numChange', 0);
						}
						this.choiceAll = true;
					} else {
						this.$emit('changeGoodsSku', {});
						this.choiceAll = false;
					}
				} else {
					this.$emit('changeGoodsSku', {});
					this.choiceAll = false;
				}
				this.$emit('changeSpec', this.goodsSpecData);
			},


			touchMove() {
				return;
			},
			hideModalSku() {
				this.$emit('changeModalSku', false);
			},
			numChange(val) {
				this.$emit('numChange', val);
			},
			
			// 购买/加入购物车前,判断限购
			checkQuota(e) {
				if (e.currentTarget.dataset.id <= 0) {
					uni.showModal({
						content: '当前商品库存为0',
						confirmColor: '#ff0000',
						success(res) {

						}
					});
					return
				}
				const data = [{
					spuid: this.goodsSpu.id,
					num: this.cartNum
				}]
				if (this.activityId) {
					data[0].activityId = this.activityId
					data[0].skuid = this.goodsSku.id
					api.checkGoodsspuQuota(JSON.stringify(data)).then(res => {
						console.log(res.data, 'res.data')
						if (res.code == 0) {							
							if (res.data) {
								if(res.data.isPressell=='1'){
									const mess = `您已经购买了${res.data.buyed}个，还能再购买${res.data.canbuy}个`
									uni.showModal({
										content: mess,
										showCancel: false,										
									})
									return
								}else{
									uni.showModal({
										content: res.data.msg,
										confirmText: "确认购买",
										cancelText: "再想想",
										success: (res1) => {
											if (res1.confirm) {
												// 活动商品超出限购部分原价购买
												this.toDo1(e, res.data.canbuy,this.cartNum - Number(res.data.canbuy),res.data.saleprice) 
											}
										}
									})
								}								
							} else {
								this.toDo(e)
							}
						}
					})
				} else {
					api.checkGoodsspuQuota(JSON.stringify(data)).then(res => {
						if (res.code == 0) {
							this.toDo(e)
						}
					})
				}
			},

			//提交
			toDo(e) {
				let canDo = true;
				try {
					this.goodsSpecData.forEach(function(spec) {
						if (!spec.checked) {
							canDo = false;
							uni.showToast({
								title: '请选择' + spec.value,
								icon: 'none',
								duration: 2000
							});
							throw new Error();
						}
					});
				} catch (e) {}

				if (this.cartNum < 1 && e.currentTarget.dataset.type != '1') { //如果选择的数量小于1,那么就不能进行购买操作，可以加入购物车
					uni.showToast({
						title: '数量必须大于0',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				if (canDo) {
					console.log('this.goodsSpu', this.goodsSpu)
					let goodsSpu = this.goodsSpu;
					let goodsSku = this.goodsSku;
					let borderArr = [];
					let specInfo = '';
					let goodsSpecData = this.goodsSpecData;
					goodsSpecData.forEach(function(spec, index) {
						spec.leaf.forEach(function(specItem) {
							if (spec.checked == specItem.id) {
								specInfo = specInfo + specItem.value;
								if (goodsSpecData.length != index + 1) {
									specInfo = specInfo + ';';
								}
							}
						});
					});

					if (e.currentTarget.dataset.type == '1') {
						//加购物车						
						console.log(this.shoppingCartId, 'uiuiuioop[poiu]')
						if (this.shoppingCartId) {
							api.shoppingCartEdit({
								shopId: this.shopId,
								id: this.shoppingCartId,
								spuId: goodsSpu.id,
								skuId: goodsSku.id,
								quantity: this.cartNum,
								addPrice: goodsSku.salesPrice == 0 ? goodsSku.marketPrice : goodsSku.salesPrice,
								spuName: goodsSpu.name,
								specInfo: specInfo,
								picUrl: goodsSku.picUrl ? goodsSku.picUrl : goodsSpu.picUrls[0],
								isVirtualGoods: goodsSpu.isVirtualGoods, // 测试 是虚拟商品
								sendType: goodsSpu.sendType, // 测试 不需要发货
								isRefund: goodsSpu.isRefund //测试 可退款
							}).then(res => {
								uni.showToast({
									title: '修改成功',
									duration: 5000
								});
								this.hideModalSku();
								this.$emit('operateCartEvent');
							});
						} else {
							const drid = uni.getStorageSync('drid');
							api.shoppingCartAdd({
								spuId: goodsSpu.id,
								activityId: this.activityId == "" ? undefined : this.activityId,
								drid: drid,
								skuId: goodsSku.id,
								quantity: this.cartNum,
								// addPrice: goodsSku.salesPrice == 0 ? goodsSku.marketPrice : goodsSku.salesPrice,
								addPrice: (this.activityId || !goodsSpu.marketingPrice) ? goodsSku.salesPrice:goodsSpu.marketingPrice,
								shopId: this.shopId,
								spuName: goodsSpu.name,
								specInfo: specInfo,
								picUrl: goodsSku.picUrl ? goodsSku.picUrl : goodsSpu.picUrls[0],
								isVirtualGoods: goodsSpu.isVirtualGoods, // 测试 是虚拟商品
								sendType: goodsSpu.sendType, // 测试 不需要发货
								isRefund: goodsSpu.isRefund //测试 可退款
							}).then(res => {
								uni.showToast({
									title: '添加成功',
									duration: 5000
								});

								this.hideModalSku();
								this.$emit('operateCartEvent');
							});
						}
						// 直播埋点
						const liveP = {
							spuId: goodsSpu.id,
							shopId: this.shopId,
						}
						if(this.activityId) {
							liveP.activityId = this.activityId
						}						
						app.liveActionShare('加入购物车',JSON.stringify(liveP))
					} else {
						const drid = uni.getStorageSync('drid');
						//立即购买，前去确认订单
						/* 把参数信息异步存储到缓存当中 */
						uni.setStorage({
							key: 'param-orderConfirm',
							data: [{
								activityId: this.activityId == "" ? undefined : this.activityId,
								clientType: goodsSpu.type,
								drid: drid,
								prescript: this.prescript,
								shopId: this.shopId,
								spuId: goodsSpu.id,
								skuId: goodsSku.id,
								quantity: this.cartNum,
								// salesPrice: goodsSku.salesPrice == 0 ? goodsSku.marketPrice : goodsSku
								// 	.salesPrice,
								salesPrice: (this.activityId || !goodsSpu.marketingPrice) ? goodsSku.salesPrice:goodsSpu.marketingPrice,
								spuName: goodsSpu.name,
								specInfo: specInfo,
								shopInfo: this.shopInfo,
								picUrl: goodsSku.picUrl ? goodsSku.picUrl : goodsSpu.picUrls[0],
								pointsDeductSwitch: goodsSpu.pointsDeductSwitch,
								pointsDeductScale: goodsSpu.pointsDeductScale,
								pointsDeductAmount: goodsSpu.pointsDeductAmount,
								pointsGiveSwitch: goodsSpu.pointsGiveSwitch,
								pointsGiveNum: goodsSpu.pointsGiveNum,
								freightTemplat: goodsSpu.freightTemplat,
								weight: goodsSku.weight,
								volume: goodsSku.volume,
								isVirtualGoods: goodsSpu.isVirtualGoods, // 测试 是虚拟商品
								sendType: goodsSpu.sendType, // 测试 不需要发货
								isRefund: goodsSpu.isRefund //测试 可退款
							}]
						});
						const value = uni.getStorageSync('prescript');
						this.prescript = value
						borderArr.push(goodsSpu.isBorder)
						uni.navigateTo({
							url: '/pages/order/order-confirm/index?prescript=' + this.prescript + '&borderArr=' +
								borderArr + '&activityId=' + this.activityId
						});
					}
					this.initFirst = true;
				}
			},

			// 活动商品超出限购部分原价购买
			toDo1(e, aBuy,oBuy,oSaleprice) {
				let canDo = true;
				try {
					this.goodsSpecData.forEach(function(spec) {
						if (!spec.checked) {
							canDo = false;
							uni.showToast({
								title: '请选择' + spec.value,
								icon: 'none',
								duration: 2000
							});
							throw new Error();
						}
					});
				} catch (e) {}

				if (this.cartNum < 1 && e.currentTarget.dataset.type != '1') { //如果选择的数量小于1,那么就不能进行购买操作，可以加入购物车
					uni.showToast({
						title: '数量必须大于0',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				if (canDo) {
					console.log('this.goodsSpu', this.goodsSpu)
					let goodsSpu = this.goodsSpu;
					let goodsSku = this.goodsSku;
					let borderArr = [];
					let specInfo = '';
					let goodsSpecData = this.goodsSpecData;
					goodsSpecData.forEach(function(spec, index) {
						spec.leaf.forEach(function(specItem) {
							if (spec.checked == specItem.id) {
								specInfo = specInfo + specItem.value;
								if (goodsSpecData.length != index + 1) {
									specInfo = specInfo + ';';
								}
							}
						});
					});

					const drid = uni.getStorageSync('drid');
					const data = []
					if (Number(aBuy) > 0) {
						data.push({
							activityId: this.activityId == "" ? undefined : this.activityId,
							clientType: goodsSpu.type,
							drid: drid,
							prescript: this.prescript,
							shopId: this.shopId,
							spuId: goodsSpu.id,
							skuId: goodsSku.id,
							quantity: aBuy,
							salesPrice: goodsSku.salesPrice,
							spuName: goodsSpu.name,
							specInfo: specInfo,
							shopInfo: this.shopInfo,
							picUrl: goodsSku.picUrl ? goodsSku.picUrl : goodsSpu.picUrls[0],
							pointsDeductSwitch: goodsSpu.pointsDeductSwitch,
							pointsDeductScale: goodsSpu.pointsDeductScale,
							pointsDeductAmount: goodsSpu.pointsDeductAmount,
							pointsGiveSwitch: goodsSpu.pointsGiveSwitch,
							pointsGiveNum: goodsSpu.pointsGiveNum,
							freightTemplat: goodsSpu.freightTemplat,
							weight: goodsSku.weight,
							volume: goodsSku.volume,
							isVirtualGoods: goodsSpu.isVirtualGoods, // 测试 是虚拟商品
							sendType: goodsSpu.sendType, // 测试 不需要发货
							isRefund: goodsSpu.isRefund //测试 可退款
						})
					}
					if(oBuy>0){
						data.push({
							clientType: goodsSpu.type,
							drid: drid,
							prescript: this.prescript,
							shopId: this.shopId,
							spuId: goodsSpu.id,
							skuId: goodsSku.id,
							quantity: oBuy+'',
							salesPrice: oSaleprice, 
							spuName: goodsSpu.name,
							specInfo: specInfo,
							shopInfo: this.shopInfo,
							picUrl: goodsSku.picUrl ? goodsSku.picUrl : goodsSpu.picUrls[0],
							pointsDeductSwitch: goodsSpu.pointsDeductSwitch,
							pointsDeductScale: goodsSpu.pointsDeductScale,
							pointsDeductAmount: goodsSpu.pointsDeductAmount,
							pointsGiveSwitch: goodsSpu.pointsGiveSwitch,
							pointsGiveNum: goodsSpu.pointsGiveNum,
							freightTemplat: goodsSpu.freightTemplat,
							weight: goodsSku.weight,
							volume: goodsSku.volume,
							isVirtualGoods: goodsSpu.isVirtualGoods, // 测试 是虚拟商品
							sendType: goodsSpu.sendType, // 测试 不需要发货
							isRefund: goodsSpu.isRefund //测试 可退款
						})
					}
					//立即购买，前去确认订单
					/* 把参数信息异步存储到缓存当中 */
					uni.setStorage({
						key: 'param-orderConfirm',
						data: data
					});
					const value = uni.getStorageSync('prescript');
					this.prescript = value
					borderArr.push(goodsSpu.isBorder)
					uni.navigateTo({
						url: '/pages/order/order-confirm/index?prescript=' + this.prescript + '&borderArr=' +
							borderArr + '&activityId=' + this.activityId
					});
					this.initFirst = true;
				}
			}
		}
	};
</script>
<style>
	.m-sku-bn {
		width: 45%;
	}

	.row-img {
		width: 240rpx !important;
		height: 240rpx !important;
		border-radius: 10rpx;
	}

	.dialo-sku {
		height: 80%;
	}

	.cu-modal {
		text-align: unset;
	}

	.close-icon {
		position: absolute;
		right: 20rpx;
		top: 20rpx;
	}
</style>
